﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Reflection;
using Microsoft.XLANGs.BaseTypes;
using Microsoft.BizTalk.ExplorerOM;
using Microsoft.Win32;

namespace Diagonal.Biztalk.SchemaExplorer
{
    public class GetSchema
    {
        public string ConnectionString { get; set; }

        public GetSchema()
        {
            // defaults
            using (var rk = Registry.LocalMachine)
            using (var sk = rk.OpenSubKey(@"SOFTWARE\Microsoft\BizTalk Server\3.0\Administration"))
            {
                ConnectionString = string.Format("Integrated Security=SSPI;database={0};server={1}", sk.GetValue("MgmtDBName"), sk.GetValue("MgmtDBServer"));
            }

        }

        public string GetSchemaText(string className)
        {
            return GetSchemaText(className, "");
        }

        public string GetSchemaText(string className, string version)
        {
            BtsCatalogExplorer cat = new BtsCatalogExplorer();
            cat.ConnectionString = ConnectionString;

            var found = (from s in cat.Schemas.Cast<Schema>()
                         where s.FullName == className && (s.BtsAssembly.Version == version || version  == "")
                         select s.XmlContent).FirstOrDefault();
            
            return found;
        }

        public List<BiztalkSchema> GetAllSchemasAsList()
        {
            // We can databind better to a list.
            return GetAllSchemas().ToList();
        }
        public IEnumerable<BiztalkSchema> GetAllSchemas()
        {
            var lastfullname = "";
            BtsCatalogExplorer cat = new BtsCatalogExplorer();
            cat.ConnectionString = ConnectionString;

            foreach (Schema btss in cat.Schemas)
            {

                if (btss.Application.Name != "BizTalk.System")
                {
                    if (btss.FullName != lastfullname)
                        yield return new BiztalkSchema() { Application = btss.Application.Name, SchemaName = btss.FullName, Version = btss.BtsAssembly.Version };
                    lastfullname = btss.FullName;
                }
            }
        }
    }
}

